package com.zxx.flowerstore.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zxx.flowerstore.entity.constant.MagicConstant;
import com.zxx.flowerstore.entity.enums.ResultEnum;
import com.zxx.flowerstore.entity.thirdService.imap.Geocodes;
import com.zxx.flowerstore.entity.thirdService.imap.IMapResult;
import com.zxx.flowerstore.service.IMapService;
import com.zxx.flowerstore.utils.common.Result;
import com.zxx.flowerstore.utils.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @ClassName IMapServiceImpl
 * @Author Admin
 * @Date 2021/4/3 8:10
 * @Description IMapServiceImpl
 * @Version 1.0
 */
@Service
public class IMapServiceImpl implements IMapService {

    @Value("${imap.key}")
    private String accessKeyID;

    private static final Logger logger = LoggerFactory.getLogger(IMapServiceImpl.class);

    @Override
    public Result getDetailByLocationName(String locationName) {
        if (StringUtils.isEmpty(locationName)) {
            return Result.error("请传入地址");
        }
        String url = MagicConstant.IMAP_BASE_URL+"?address="+locationName+"&output=JSON&key="+accessKeyID;
        String imapRes;
        try {
            imapRes = HttpUtils.getJSON(url);
        } catch (Exception me) {
            logger.error("调用高德地图："+me.getMessage());
            return Result.error(ResultEnum.ERROR.getCode(), "调用高德失败");
        }
        if (StringUtils.isEmpty(imapRes)) {
            return Result.error(ResultEnum.ERROR.getCode(), "调用高德失败");
        }
        IMapResult iMapResult = JSONObject.parseObject(imapRes,IMapResult.class);
        return Result.success(CollectionUtils.isEmpty(iMapResult.getGeocodes())? new ArrayList<Geocodes>():iMapResult.getGeocodes());
    }
}
